659E - New Reform - CodeForces Solution


data structures dfs and similar dsu graphs greedy *1600

Please click on ads to support us..

Python Code:

def dfs(node, prev_node):
    global flag
    if node not in visited:
        if flag:
            visited.add(node)
        else:
            flag = True
        ret = True
        for n in arcs[node]:
            if prev_node != n:
                ret = ret and dfs(n,node)
        return ret

cities, roads = list(map(int,input().split()))
arcs = {k+1: [] for k in range(cities)}
flag = False
visited = set()
min = 0


for _ in range(roads):
    a,b = list(map(int,input().split()))
    arcs[a].append(b)
    arcs[b].append(a)

for n in range(1,cities+1):
    if n not in visited:
        if(dfs(n,0)):
            min +=1
print(min)

C++ Code:

#include <bits/stdc++.h>
#define rep(i,n) for (long long i=0; i<n; ++i)
#define isodd %2==1
#define iseven %2==0
#define ll long long
#define ld long double
#define pb push_back
#define mp make_pair
#define all(v) v.begin(),v.end()
#define back(v) v.rbegin(),v.rend()
#define vi vector<ll>
#define vb vector<bool>
#define IOS ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
using namespace std;
bool dfs(ll node,vb &vis,vector<vi> &adj,ll parent){
    vis[node]= true;
    bool ans = false;
    for(auto it:adj[node]){
        if(!vis[it]){
            if(dfs(it,vis,adj,node)) {
                    ans= true;
            } 
        }
        else if(it!=parent) {
            ans= true;
        };
    }
    return ans;
}
void sol(){
    ll n,m;
    cin>>n>>m;
    vector<vi> adj(n+1);
    for (ll i = 0; i < m; i++)
    {
        ll x,y;cin>>x>>y;
        adj[x].push_back(y);
        adj[y].push_back(x);
    }
    ll cnt=0;
    vb vis(n+1,0);
    for (ll i = 1; i <= n; i++)
    {
        if(!vis[i]){
            if(!dfs(i,vis,adj,-1)){
                cnt++;
            }
        }
    }
    cout<<cnt<<'\n';
    
    
}
int main()
{IOS;

    sol();

    
    return 0;
}


Comments

Submit
0 Comments
More Questions

1692B - All Distinct
1156C - Match Points
1675A - Food for Animals
1328C - Ternary XOR
1689A - Lex String
1708B - Difference of GCDs
863A - Quasi-palindrome
1478A - Nezzar and Colorful Balls
1581B - Diameter of Graph
404A - Valera and X
908A - New Year and Counting Cards
146A - Lucky Ticket
1594C - Make Them Equal
1676A - Lucky
1700B - Palindromic Numbers
702C - Cellular Network
1672C - Unequal Array
1706C - Qpwoeirut And The City
1697A - Parkway Walk
1505B - DMCA
478B - Random Teams
1705C - Mark and His Unfinished Essay
1401C - Mere Array
1613B - Absent Remainder
1536B - Prinzessin der Verurteilung
1699B - Almost Ternary Matrix
1545A - AquaMoon and Strange Sort
538B - Quasi Binary
424A - Squats
1703A - YES or YES